//
//  JGMainViewController.m
//  Netease_Project
//
//  Created by JJetGu on 15-6-17.
//  Copyright (c) 2015年 JJetGu. All rights reserved.
//

#import "JGMainViewController.h"
#import "JGLeftMenu.h"
#import "JGTitleView.h"
#import "JGNavigationViewController.h"
#import "JGNewsTableViewController.h"
#import "JGReadingTableViewController.h"
#import "JGRightMenuController.h"

static const float speedf = 0.5;

#define JGNavShowAnimDuration 0.25

#define JGCoverTag 99

#define JGLeftMenuW 206
#define JGLeftMenuH 300
#define JGLeftMenuY 50

#define JGRightMenuW 260

@interface JGMainViewController ()<JGLeftMenuDelegate>
{
     CGFloat _scalef;
}
/**
 *  正在显示的导航控制器
 */
@property (nonatomic, weak) JGNavigationViewController *showingNavigationController;
@property (nonatomic, strong)JGRightMenuController *rightMenuVc;
@property (nonatomic, weak)JGLeftMenu *leftMenu;
@end

@implementation JGMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    UIImageView *imageview = [[UIImageView alloc]init];
    imageview.userInteractionEnabled = YES;
    imageview.image = [UIImage imageNamed:@"sidebar_bg@2x.jpg"];
    imageview.frame = self.view.bounds;
    [self.view addSubview:imageview];
    
    // 1.创建子控制器
    [self setupAllChildVcs];
    
    // 2.添加左菜单
    [self setupLeftMenuInView:imageview];
    
    // 3.添加右菜单
    [self setupRightMenuInView:imageview];
}

/**
 *  添加右菜单
 */
- (void)setupRightMenuInView:(UIImageView *)imageview
{
    JGRightMenuController *rightMenuVc = [[JGRightMenuController alloc]init];
    rightMenuVc.view.width = JGRightMenuW;
    rightMenuVc.view.x = self.view.width - rightMenuVc.view.width;
    [imageview addSubview:rightMenuVc.view];
    self.rightMenuVc = rightMenuVc;
}

/**
 *  添加左菜单
 */
- (void)setupLeftMenuInView:(UIImageView *)imageview
{
    JGLeftMenu *leftMenu = [[JGLeftMenu alloc] init];
    leftMenu.delegate = self;
    leftMenu.height = JGLeftMenuH;
    leftMenu.width = JGLeftMenuW;
    leftMenu.y = JGLeftMenuY;
    [imageview addSubview:leftMenu];
     self.leftMenu = leftMenu;
}

/**
 *  创建子控制器
 */
- (void)setupAllChildVcs
{
    JGNewsTableViewController *news = [[JGNewsTableViewController alloc] init];
    [self setupVc:news title:@"新闻"];
    
    JGReadingTableViewController *reading = [[JGReadingTableViewController alloc] init];
    [self setupVc:reading title:@"订阅"];
    
    UIViewController *photo = [[UIViewController alloc] init];
    [self setupVc:photo title:@"图片"];
    
    UIViewController *video = [[UIViewController alloc] init];
    [self setupVc:video title:@"视频"];
    
    UIViewController *comment = [[UIViewController alloc] init];
    [self setupVc:comment title:@"跟帖"];
    
    UIViewController *radio = [[UIViewController alloc] init];
    [self setupVc:radio title:@"电台"];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

/**
 *  初始化一个控制器
 *
 *  @param vc      需要初始化的控制器
 *  @param title   控制器的标题
 */
- (void)setupVc:(UIViewController *)vc title:(NSString *)title
{
    // 1.设置背景色
    vc.view.backgroundColor = HMRandomColor;
    
    // 2.设置标题
    JGTitleView *titleView = [[JGTitleView alloc] init];
    titleView.title = title;
    vc.navigationItem.titleView = titleView;
    
     // 3.设置左右按钮
    vc.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithImageName:@"top_navigation_menuicon" target:self action:@selector(leftMenuClick)];
    vc.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"top_navigation_infoicon" target:self action:@selector(rightMenuClick)];
    // 4.包装一个导航控制器
    JGNavigationViewController *nav = [[JGNavigationViewController alloc] initWithRootViewController:vc];
    
    //5.添加滑动手势
    UIPanGestureRecognizer * pan = [[UIPanGestureRecognizer alloc]initWithTarget:self action:@selector(handlePan:)];
    [nav.view addGestureRecognizer:pan];

    //6.添加点击手势
    UITapGestureRecognizer *sideslipTapGes = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(handeTap:)];
    [sideslipTapGes setNumberOfTapsRequired:1];
    [nav.view addGestureRecognizer:sideslipTapGes];
    
    // 让newsNav成为self（HMMainViewController）的子控制器，能保证：self在，newsNav就在
    // 如果两个控制器互为父子关系，那么它们的view也应该互为父子关系
    [self addChildViewController:nav];
}

#pragma mark - 监听导航栏按钮点击

- (void)leftMenuClick
{
    //当手势情况下，点击无效
    if (self.showingNavigationController.view.centerX > self.view.centerX) {
        return;
    }
    
    self.leftMenu.hidden = NO;
    self.rightMenuVc.view.hidden = YES;
    
    [UIView animateWithDuration:JGNavShowAnimDuration animations:^{
        // 取出正在显示的导航控制器的view
        UIView *showingView = self.showingNavigationController.view;
        
        //缩放比例
        CGFloat navH = [UIScreen mainScreen].bounds.size.height - 2 * JGLeftMenuY;
        CGFloat scale = navH / [UIScreen mainScreen].bounds.size.height;
        
        // 菜单左边的间距
        CGFloat leftMenuMargin = [UIScreen mainScreen].bounds.size.width * (1 - scale) * 0.5;
         CGFloat translateX = JGLeftMenuW - leftMenuMargin;
        
        CGFloat topMargin = [UIScreen mainScreen].bounds.size.height * (1 - scale) * 0.5;
        CGFloat translateY = JGLeftMenuY -  topMargin;
        
        // 缩放
        CGAffineTransform scaleForm = CGAffineTransformMakeScale(scale, scale);
        // 平移
        CGAffineTransform translateForm = CGAffineTransformTranslate(scaleForm, translateX / scale, translateY / scale);
        
         showingView.transform = translateForm;
        
        // 添加一个遮盖
        UIButton *cover = [[UIButton alloc] init];
        cover.tag = JGCoverTag;
        [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
        cover.frame = showingView.bounds;
        [showingView addSubview:cover];
        
    }];
}

- (void)coverClick:(UIView *)cover
{
    [UIView animateWithDuration:JGNavShowAnimDuration animations:^{
        self.showingNavigationController.view.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        [cover removeFromSuperview];
    }];
}

- (void)rightMenuClick
{
    //当手势情况下，点击无效
    if (self.showingNavigationController.view.centerX < self.view.centerX) {
        return;
    }
    
    self.leftMenu.hidden = YES;
    self.rightMenuVc.view.hidden = NO;
    
    [UIView animateWithDuration:JGNavShowAnimDuration animations:^{
        // 取出正在显示的导航控制器的view
        UIView *showingView = self.showingNavigationController.view;
        
        // 缩放比例
        CGFloat navH = [UIScreen mainScreen].bounds.size.height - 2 * JGLeftMenuY;
        CGFloat scale = navH / [UIScreen mainScreen].bounds.size.height;
        
        // 菜单左边的间距
        CGFloat leftMenuMargin = [UIScreen mainScreen].bounds.size.width * (1 - scale) * 0.5;
        CGFloat translateX = leftMenuMargin - self.rightMenuVc.view.width;
        
        CGFloat topMargin = [UIScreen mainScreen].bounds.size.height * (1 - scale) * 0.5;
        CGFloat translateY = JGLeftMenuY - topMargin;
        
        // 缩放
        CGAffineTransform scaleForm = CGAffineTransformMakeScale(scale, scale);
        // 平移
        CGAffineTransform translateForm = CGAffineTransformTranslate(scaleForm, translateX / scale, translateY / scale);
        
        showingView.transform = translateForm;
        
        // 添加一个遮盖
        UIButton *cover = [[UIButton alloc] init];
        cover.tag = JGCoverTag;
        [cover addTarget:self action:@selector(coverClick:) forControlEvents:UIControlEventTouchUpInside];
        cover.frame = showingView.bounds;
        [showingView addSubview:cover];
    } completion:^(BOOL finished) {
        //展示3D旋转动画
         [self.rightMenuVc didShow];
    }];
}

#pragma mark - 滑动手势
- (void) handlePan: (UIPanGestureRecognizer *)rec{
    
    CGPoint point = [rec translationInView:self.view];
    _scalef = (point.x*speedf+_scalef);
    
    //根据视图位置判断是左滑还是右边滑动
    if (rec.view.frame.origin.x>=0){
        rec.view.center = CGPointMake(rec.view.center.x + point.x*speedf,rec.view.center.y);
        rec.view.transform = CGAffineTransformScale(CGAffineTransformIdentity,1-_scalef/1000,1-_scalef/1000);
        [rec setTranslation:CGPointMake(0, 0) inView:self.view];
        
        self.leftMenu.hidden = NO;
        self.rightMenuVc.view.hidden = YES;
        
    }
    else
    {
        rec.view.center = CGPointMake(rec.view.center.x + point.x*speedf,rec.view.center.y);
        rec.view.transform = CGAffineTransformScale(CGAffineTransformIdentity,1+_scalef/1000,1+_scalef/1000);
        [rec setTranslation:CGPointMake(0, 0) inView:self.view];

        self.leftMenu.hidden = YES;
        self.rightMenuVc.view.hidden = NO;
    }
    
    //手势结束后修正位置
    if (rec.state == UIGestureRecognizerStateEnded) {
        if (_scalef>140*speedf){
            [self showLeftView];
        }
        else if (_scalef<-140*speedf) {
            [self showRighView];
        }
        else
        {
            [self showMainView];
            _scalef = 0;
        }
    }
    
}

#pragma mark - 单击手势
-(void)handeTap:(UITapGestureRecognizer *)tap{
    if (tap.state == UIGestureRecognizerStateEnded) {
        [UIView beginAnimations:nil context:nil];
        tap.view.transform = CGAffineTransformScale(CGAffineTransformIdentity,1.0,1.0);
        tap.view.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2,[UIScreen mainScreen].bounds.size.height/2);
        [UIView commitAnimations];
        _scalef = 0;
    }
}

#pragma mark - 手势结束后修改视图位置
//恢复位置
-(void)showMainView{
    [UIView beginAnimations:nil context:nil];
    self.showingNavigationController.view.transform = CGAffineTransformScale(CGAffineTransformIdentity,1.0,1.0);
    self.showingNavigationController.view.center = CGPointMake([UIScreen mainScreen].bounds.size.width/2,[UIScreen mainScreen].bounds.size.height/2);
    [UIView commitAnimations];
}

//显示左视图
-(void)showLeftView{
    [UIView beginAnimations:nil context:nil];
    self.showingNavigationController.view.transform = CGAffineTransformScale(CGAffineTransformIdentity,0.83,0.83);
    self.showingNavigationController.view.center = CGPointMake(340,[UIScreen mainScreen].bounds.size.height/2);
    [UIView commitAnimations];
    
}

//显示右视图
-(void)showRighView{
    
    [self.rightMenuVc didShow];
    
    [UIView beginAnimations:nil context:nil];
    self.showingNavigationController.view.transform = CGAffineTransformScale(CGAffineTransformIdentity,0.8,0.8);
    self.showingNavigationController.view.center = CGPointMake(-60,[UIScreen mainScreen].bounds.size.height/2);
    [UIView commitAnimations];
}

#pragma mark - HMLeftMenuDelegate
-(void)leftMenu:(JGLeftMenu *)menu didSelectedButtonFromIndex:(NSInteger)fromIndex toIndex:(NSInteger)toIndex
{
    // 0.移除旧控制器的view
    JGNavigationViewController *oldNav = self.childViewControllers[fromIndex];
    [oldNav.view removeFromSuperview];

    // 1.显示新控制器的view
    JGNavigationViewController *newNav = self.childViewControllers[toIndex];
    [self.view addSubview:newNav.view];
    
    // 2.设置新控制的transform跟旧控制器一样
    newNav.view.transform = oldNav.view.transform;
    
    // 设置阴影
    newNav.view.layer.shadowColor = [UIColor blackColor].CGColor;
    newNav.view.layer.shadowOffset = CGSizeMake(-3, 0);
    newNav.view.layer.shadowOpacity = 0.2;
    
    // 一个导航控制器的view第一次显示到它的父控件上时，如果transform的缩放值被改了，上面的20高度当时是不会出来
    
    // 3.设置当前正在显示的控制器
    self.showingNavigationController = newNav;
    
    // 3.清空transform-- 切换之后直接回来
    [self coverClick:[newNav.view viewWithTag:JGCoverTag]];
    
}

@end
